import axios, { AxiosHeaders } from "axios";
// 把 vant 的 Dialog 组件拿过来
import { Dialog } from "vant";
import type { AxiosRequestConfig } from "axios";

// 创建 axios 实例
const instance = axios.create({
  baseURL: "http://47.94.148.165:3001/api",
  timeout: 5000,
});

interface myAxiosRequestConfig extends AxiosRequestConfig {
  headers: { token?: string | null }
}

// 配置请求拦截器
instance.interceptors.request.use((config: AxiosRequestConfig) => {
  // 判断是 获取用户信息
  if (config.url === "/user/info") {
    (config.headers as AxiosRequestConfig<AxiosHeaders>).token =
      window.localStorage.getItem("token");
  }
  // 购物车相关
  if (/^\/cart/.test(config.url as string)) {
    // 拿到 token 进行添加
    // (config.headers as AxiosRequestConfig<AxiosHeaders>).token = window.localStorage.getItem('token')
    (config as myAxiosRequestConfig).headers.token = window.localStorage.getItem('token')
  }

  // 查询所有订单
  if (config.url === '/user/orderlist') {
    // (config.headers as AxiosRequestConfig<AxiosHeaders>).token = window.localStorage.getItem('token')
    (config as myAxiosRequestConfig).headers.token = window.localStorage.getItem('token')
  }
  return config;
});

// 配置响应拦截器
instance.interceptors.response.use(
  response => {
    // code 为 '10119'
    if (response.data.code === '10119') {
      Dialog({
        title: '提示',
        message: '您登录状态有问题, 请重新登录'
      })

      return { code: 0 }
    }
    return response.data;
  },
  (err) => {
    Dialog.alert({ title: "网络错误", message: "网络不给力, 稍后再来" });
  }
);
// 导出实例
export default instance;
